﻿using KPIS.GERP.Models.Class;
using System;
using System.Linq;
using System.Web.Mvc;
using KPIS.GERP.Models.ICM;
using Resources;
using System.Collections.Generic;
using System.Data;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class CommitteeController : Controller
    {
        private string[] _basicIncludeSubclass = new[]
            {
                "CommitteeType", "CommitteePosition", "CommitteeFunction"
            };

        private string[] _basicIncludeSubclassGroup = new[]
            {
                "Committees.CommitteeType", "Committees.CommitteePosition", "Committees.CommitteeFunction"
            };

        public ActionResult Index(int committeeGroupId, bool EmptyLayout = false)
        {
            var service = new CommitteeGroupService.CommitteeGroupServiceClient();
            ViewBag.committeeGroupId = committeeGroupId;
            ViewBag.EmptyLayout = EmptyLayout;
            var data = service.Select(new CommitteeGroup
                {
                    CommitteeGroupId = committeeGroupId,
                    RecordStatus = "!" + Models.SYS.RecordStatus.DeletedStatus
                }, _basicIncludeSubclassGroup).First();

            data.Committees = data.Committees.Where(m => m.RecordStatus != "D").ToList();

            // Load position name
            var employees = new EmployeeService.EmployeeServiceClient().Select(null, new[]
                {
                    "Position"
                }, null);

            if (data.Committees != null)
                foreach (var d in data.Committees)
                {
                    if (string.IsNullOrWhiteSpace(d.EmpPositionName))
                    {
                        var emp = employees.FirstOrDefault(o => o.EmpId == d.EmpId);
                        d.EmpPositionName = emp != null && emp.Position != null ? emp.Position.Name : string.Empty;
                    }
                }

            return View(data.Committees);
        }

        public ActionResult Details(int id)
        {
            var service = new CommitteeService.CommitteeServiceClient();
            var model = service.Select(new Committee
                {
                    CommitteeId = id,
                    RecordStatus = "!D"
                }, _basicIncludeSubclass).FirstOrDefault();
            return View(model);
        }

        public ActionResult Create(int committeeGroupId)
        {
            var model = new Committee();
            model.CommitteeGroupId = committeeGroupId;
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Committee model, FormCollection collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new CommitteeService.CommitteeServiceClient();
                    var id = service.Insert(model, Class.GimsMembership.CurrentEmpId);
                    return RedirectToAction("Details", new
                        {
                            id
                        });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return View(model);
        }

        public ActionResult Edit(int id)
        {
            var service = new CommitteeService.CommitteeServiceClient();
            var model = service.Select(new Committee
                {
                    CommitteeId = id,
                    RecordStatus = "!D"
                }, _basicIncludeSubclass).FirstOrDefault();
            return View(model);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Edit(int id, Committee model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var service = new CommitteeService.CommitteeServiceClient();
                    service.Update(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Details", new
                        {
                            id
                        });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return View(model);
        }

        public ActionResult Delete(int id)
        {
            try
            {
                var service = new CommitteeService.CommitteeServiceClient();
                var model = service.Select(new Committee() { CommitteeId=id }, null).FirstOrDefault();
                service.Delete(id, Class.GimsMembership.CurrentEmpId);
                service.Close();
                return RedirectToAction("Index", new { committeeGroupId = model.CommitteeGroupId });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult DeleteAll(int[] deleteIds)
        {
            if (deleteIds == null)
                return Json(new
                    {
                        success = true
                    });

            try
            {
                var service = new CommitteeService.CommitteeServiceClient();
                foreach (int delete in deleteIds)
                {
                    service.Delete(delete, Class.GimsMembership.CurrentEmpId);
                }

                ModelState.AddModelError(ErrorLocalization.Error, string.Format("ลบข้อมูลไปทั้งหมด {0} รายการ", deleteIds.Length.ToString("#,##0")));
                return Json(new
                    {
                        success = true
                    });
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(ErrorLocalization.Error, ErrorLocalization.ErrorWhileDeleteData);
                GerpLog.Error(ErrorLocalization.ErrorWhileDeleteData + ", " + ex.Message);
                return Json(new
                    {
                        success = false
                    });
            }
        }

        public ActionResult GetEmployeeDetails(int id)
        {
            var service = new EmployeeService.EmployeeServiceClient();
            var result = service.Select(new Models.HRM.Employee()
                {
                    EmpId = id
                }, new[]
                    {
                        "Position", "JobSite"
                    }, null).FirstOrDefault();

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public void Report(int committeeGroupId)
        {
            Dictionary<string, string> fields = new Dictionary<string, string>();
            Dictionary<string, DataTable> Table = new Dictionary<string, DataTable>();
            MailMerge mailMerge = new MailMerge();
            var ServiceCommittee = new CommitteeService.CommitteeServiceClient();
            var ServiceCommitteeGroup = new CommitteeGroupService.CommitteeGroupServiceClient();
            var ServicePpr = new PrePurchaseRequestService.PrePurchaseRequestServiceClient();

            //var ModelPpr = ServicePpr.Select(new PrePurchaseRequest
            //{
            //    PprId = pprId,
            //    RecordStatus = "!" + Models.SYS.RecordStatus.DeletedStatus
            //}, new[] { "MasPurchaseType", 
            //    "CommitteeGroup.Committees.CommitteeType", 
            //    "CommitteeGroup.Committees.CommitteePosition", 
            //    "CommitteeGroup.Committees.CommitteeFunction"  }).FirstOrDefault();

            var ModelCommittee = ServiceCommitteeGroup.Select(new CommitteeGroup
                {
                    CommitteeGroupId = committeeGroupId,
                    RecordStatus = "!D"
                }, _basicIncludeSubclassGroup).First().Committees;

            string ComFuncName = string.Empty;
            string EmpName = string.Empty;
            string funcname = string.Empty;
            int nIndex = 1;
            int subIndex = 1;
            if (ModelCommittee != null)
            {
                var group = ModelCommittee.GroupBy(x => x.ComFunctionId).ToList();
                for (int i = 0; i < group.Count; i++)
                {
                    //string funcname = group[i].ElementAt(i).CommitteeFunction.LookUpName;
                    //ComFuncName = ComFuncName + (funcname + " ประกอบด้วย" + (nIndex < group[i].Count() ? System.Environment.NewLine : ""));
                    //nIndex++;

                    for (int j = 0; j < group[i].Count(); j++)
                    {
                        int itemNo = j + 1;
                        string Name = group[i].ElementAt(j).EmpName;
                        string ComPos = group[i].ElementAt(j).CommitteePosition.LookUpName;
                        string PosName = "ตำแหน่ง " + group[i].ElementAt(j).EmpPositionName;
                        string eName = "(" + itemNo + ") " + Name + "\t\t\t" + ComPos + "\n\t    " + PosName;
                        EmpName = EmpName + ("\t" + eName + (subIndex < group[i].Count() ? System.Environment.NewLine : ""));
                        subIndex++;


                        for (int k = 0; k < group[i].Count(); k++)
                        {
                            int groupNo = i + 1;
                            funcname = groupNo + ". " + group[i].ElementAt(k).CommitteeFunction.LookUpName;
                        }


                    }
                    ComFuncName = ComFuncName + (funcname + " ประกอบด้วย"
                                                 + System.Environment.NewLine
                                                 + EmpName + System.Environment.NewLine
                                                 + (nIndex < group.Count() ? System.Environment.NewLine : ""));
                    nIndex++;
                    EmpName = "";
                    subIndex = 1;

                    //int groupNo = i + 1;
                    //string funcname = groupNo + ". " + group[i].ElementAt(i).CommitteeFunction.LookUpName;
                    //ComFuncName = ComFuncName + (funcname + " ประกอบด้วย"
                    //    + System.Environment.NewLine
                    //    + EmpName + System.Environment.NewLine
                    //    + (nIndex < group.Count() ? System.Environment.NewLine : ""));
                    //nIndex++;

                    //EmpName = "";
                    //subIndex = 1;
                }
            }

            var committeeGroup = ServiceCommitteeGroup.Select(new CommitteeGroup
                {
                    CommitteeGroupId = committeeGroupId
                }, null).FirstOrDefault();

            PrePurchaseRequest ModelPpr = null;

            if (committeeGroup.CreateByPprId.HasValue)
            {
                ModelPpr = ServicePpr.Select(new PrePurchaseRequest
                {
                    PprId = committeeGroup.CreateByPprId.Value
                }, new string[]
                {
                    "MasPurchaseType"
                }).First();
            }


            fields.Add("Name", ModelPpr!=null? ModelPpr.MasPurchaseType.PcTypeName + ModelPpr.Name:"");
            fields.Add("ComFunction", ComFuncName);

            string strTemplatePath = Server.MapPath("~/Templates/รายงานคำสั่งแต่งตั้งคณะกรรมการ.docx");
            string strSaveAsPath = Server.MapPath("~/Temp/");
            string strSaveAsFileName = string.Format("รายงานคำสั่งแต่งตั้งคณะกรรมการ{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmssffff"));

            if (mailMerge.MergeTemplate(strTemplatePath, strSaveAsPath + strSaveAsFileName, fields, null))
            {
                Response.Clear();
                Response.ContentType = "text/plain";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + strSaveAsFileName);
                Response.WriteFile(strSaveAsPath + strSaveAsFileName);
                Response.Flush();
                System.IO.File.Delete(strSaveAsPath + strSaveAsFileName);
                Response.End();
                //mailMerge.SaveFileToClient(strSaveAsPath, strSaveAsFileName, true);
            }
        }
    }
}